package base.copy;

/**
 * 浅拷贝
 *
 * @author liweimin
 * @date 2021/5/29 10:30
 * @since
 */
public class ShallowCopy1 {

    public static void main(String[] args) {
        Age age = new Age(24);

        Person person = new Person(age, "李二狗");

        Person person1 = new Person(person);

        System.out.println(person);
        System.out.println(person1);
        System.out.println("====================== 修改person的属性 ===================");

        //字符串在常量池中
        person.setName("lwmzzz");
        age.setAge(99);

        System.out.println(person);
        System.out.println(person1);


        Person person2 = person;


        //只是内存地址的传递，并没有在堆中创建新的对象
        System.out.println(person == person2);//true


    }

}

class Age {
    public int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Age(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Age{" +
                "age=" + age +
                '}';
    }
}

class Person {
    //引用类型
    private Age age;
    private String name;

    public Age getAge() {
        return age;
    }

    public void setAge(Age age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person(Person person) {
        //引用传递
        this.age = person.age;
        this.name = person.name;
    }

    public Person(Age age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Person{");
        sb.append("age=").append(age);
        sb.append(", name='").append(name).append('\'');
        sb.append('}');
        return sb.toString();
    }
}
